package cn.vin.ws;

import com.alibaba.fastjson.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class MsgWebSocketClient extends WebSocketClient {
    String name;
    public long startTime;
    public static final List<Long> waits = new CopyOnWriteArrayList<>();
    static AtomicInteger num = new AtomicInteger();
    int score;
    long gold;
    public MsgWebSocketClient(String name, String url) throws URISyntaxException {
        super(new URI(url));
        this.name = name;
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onOpen(ServerHandshake shake) {
        // TODO Auto-generated method stub
        System.out.println("握手...");
        /*for(Iterator<String> it = shake.iterateHttpFields(); it.hasNext();) {
            String key = it.next();
            System.out.println(key+":"+shake.getFieldValue(key));
        }*/
    }

    @Override
    public void onMessage(String paramString) {
        // TODO Auto-generated method stub
        JSONObject jsonObject = JSONObject.parseObject(paramString);
        if(jsonObject.getInteger("cmd").equals(20002)) {
            JSONObject data = jsonObject.getJSONObject("data");
            Integer score2 = data.getInteger("score");
            waits.add(System.currentTimeMillis() - startTime);
            System.out.println(name + "___" + this.score + "接收到消息："+ data.getString("openid") +"___"+score2 + (Math.abs(score2 -score) > 1000 ? "************************" : ""));
            System.out.println("匹配成功==" + num.incrementAndGet());
        } else {
            System.out.println(paramString);
        }
    }

    @Override
    public void onClose(int paramInt, String paramString, boolean paramBoolean) {
        // TODO Auto-generated method stub
        System.out.println("关闭...");
    }

    @Override
    public void onError(Exception e) {
        // TODO Auto-generated method stub
        System.out.println("异常"+e);

    }
}
